package com.lzx.lizhenxing.pay.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.request.AlipayTradeCloseRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.lzx.lizhenxing.pay.enums.PayStateEnum;
import com.lzx.lizhenxing.pay.param.PayParam;
import com.lzx.lizhenxing.pay.param.TradePayParam;
import com.lzx.lizhenxing.pay.service.PayService;
import com.lzx.lizhenxing.pay.service.TradeOrderPayService;
import com.lzx.lizhenxing.pay.vo.PayQrVO;
import com.lzx.lizhenxing.user.dao.UserOrderDao;
import com.lzx.lizhenxing.user.model.UserOrderModel;
import com.lzx.lizhenxing.user.service.UserOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class TradeOrderPayServiceImpl implements TradeOrderPayService {

    @Resource(name = "aliPayServiceImpl")
    private PayService aliPayService;

    @Resource
    private UserOrderDao userOrderDao;

    @Resource
    private UserOrderService userOrderService;

    @Resource
    private AlipayClient alipayClient;

    @Override
    public PayQrVO tradeOrderPay(TradePayParam payParam) {
        // 根据业务订单的id查询订单编号和支付金额
        UserOrderModel userOrder = userOrderDao.selectById(payParam.getOrderId());
        BigDecimal totalAmount = new BigDecimal("54");

        PayParam param = new PayParam();
        param.setTradeNo(userOrder.getOrderNo());
        param.setTotalAmount(totalAmount);
        param.setSubject("充值测试");

        String qrCodeUrl = "";
        PayQrVO vo = new PayQrVO();
        // 支付宝支付
        qrCodeUrl = aliPayService.createPayOrder(param);
        vo.setQrCodeUrl(qrCodeUrl);
        vo.setOrderNo(userOrder.getOrderNo());
        return vo;
    }

    @Override
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        aliPayService.notify(request, response);
    }

    @Override
    public Integer payStates(Long orderId) {
        try {
            UserOrderModel orderModel = userOrderDao.selectById(orderId);
            if (orderModel == null) {
                throw new RuntimeException("本地订单不存在：" + orderId);
            }

            AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            model.setOutTradeNo(orderModel.getOrderNo());
            request.setBizModel(model);
            // 设置查询选项
            List<String> queryOptions = new ArrayList<String>();
            queryOptions.add("trade_settle_info");
            model.setQueryOptions(queryOptions);

            AlipayTradeQueryResponse response = alipayClient.execute(request);
            System.out.println("查询订单响应：" + response.getBody());

            if (response.isSuccess()) {
                String tradeStatus = response.getTradeStatus();
                switch (tradeStatus) {
                    case "WAIT_BUYER_PAY":
                        return PayStateEnum.WAIT_BUYER_PAY.getType();
                    case "TRADE_SUCCESS":
                        return PayStateEnum.TRADE_SUCCESS.getType();
                    case "TRADE_CLOSED":
                        return PayStateEnum.TRADE_CLOSED.getType();
                    default:
                        return PayStateEnum.OTHER.getType();
                }
            } else {
                return PayStateEnum.UNSCENTED_CODE.getType();
            }
        } catch (AlipayApiException e) {
            log.warn("用户未扫码");
            throw new RuntimeException("查询异常：" + e.getMessage());
        }
    }

    @Override
    public Integer tradePayCancel(Long orderId) {
        // 业务订单编码
        String orderNo = userOrderService.getOrderNo(orderId);
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderNo);
        request.setBizContent(bizContent.toString());
        AlipayTradeCloseResponse response = null;
        try {
            // 发送给支付宝系统关闭交易订单
            response = alipayClient.execute(request);
            if(response.isSuccess()){
                log.info("关闭交易订单成功,业务订单号:{}",orderNo);
                // 同时需要关闭业务订单
                userOrderService.cancelOrder(orderId);
                return 1;
            } else {
                if(response.getSubMsg().equals("交易不存在")){
                    return 2;
                }
                log.info("关闭交易订单失败,业务订单号:{}",orderNo);
                return 0;
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void tradePayRefund(Long orderId) {
        String orderNo = userOrderService.getOrderNo(orderId);
        // 构造请求参数以调用接口
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        AlipayTradeRefundModel model = new AlipayTradeRefundModel();
        // 设置商户订单号
        model.setOutTradeNo(orderNo);
        // 设置退款金额
        model.setRefundAmount("54");
        // 设置退款原因说明
        model.setRefundReason("正常退款");
        request.setBizModel(model);
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
            if (response.isSuccess()) {
                log.info("退款成功：退款金额{},退款订单号：:{}","54",orderNo);
            } else {
                log.info("退款失败");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }


    }
}
